<template>
  <view class="container ">
    <view class="van_top">
      <van-nav-bar title="购物车" fixed />
    </view>
    <view class="content">
      <view class="safe-area" :style="{ height: (statusBarHeight + 46) + 'px' }" style="width: 100%;"></view>
      <view class="goods_list" v-if="goodsList.length != 0"
        :class="chajia > 0 ? 'goods_list_active' : 'goods_list_noactive'">
        <scroll-view enhanced scroll-y :show-scrollbar="false" :refresher-triggered="loading" class="scroll-Y"
          :refresher-enabled="Status == '1'" @refresherrefresh="refresherrefreshFn" style="height:calc(100%)">
          <view class="logo">
            <image src="../../static/shopcar/shoppingcar.png" alt="" style="width: 288rpx; height: 38rpx;"
              mode="aspectFit" />
            <text v-if="goodsList.length > 0 && editStatus === '0'" @click="editGoods">编辑</text>
            <text v-if="goodsList.length > 0 && editStatus === '1'" @click="cancelEditGoods">取消</text>
          </view>
          <checkbox-group @change="onChange" id="checkboxGroupId">
            <van-swipe-cell v-for="(item, index) in goodsList" :key="item.id" :right-width="65" async-close
              @close="delItemGoods($event, item.id)">
              <van-cell-group>
                <view class="goods_item">
                  <checkbox :value="item.id" :disabled="item.state == '1' && editStatus === '0'" :key="Math.random()"
                    color="#FF1642" :checked="item.checked" style="margin-right: 24rpx;" />
                  <view class="imgShowBox">
                    <image @click="goToDetail(item.ecCommodityId, item.type)" :src="item.images" alt=""
                      style="width: 180rpx; height: 180rpx;" mode="aspectFill" />
                    <view class="none" v-if="item.state == '1'">
                      <text>{{ item.releaseStock == '0' ? '已售罄' : '已下架' }}</text>
                    </view>
                  </view>
                  <view class="txtInfo">
                    <view class="goods_name">{{ item.name }}</view>
                    <view class="goods_deliveryNorms" v-if="item.type == 0">配送规格：{{ item.normsInfo }}</view>
                    <view class="goods_deliveryNorms" v-if="item.type == 1">配送规格：{{ item.deliveryNorms }}KG</view>
                    <view class="countBox">
                      <PriceFont color="#FF4F30" bigSize="40rpx" smallSize="28rpx" :price="item.normsPrice" />
                      <view class="goods_count">
                        <uni-number-box v-if="editStatus === '0' && item.state == '0'" :min="1"
                          :max="item.limitCount == 0 ? item.releaseStock : item.limitCount" :value="item.count"
                          @change="onChangecount($event, item.id, index, item.ecCommodityId, item.type)" />
                        <van-icon name="delete-o" v-if="editStatus === '1'" color="#ee0a24"
                          @click="delGoodsBtn(item.id, index)" />
                      </view>
                    </view>
                  </view>
                </view>
              </van-cell-group>
              <view slot="right">
                <view class="delBox">
                  删除
                </view>
              </view>
            </van-swipe-cell>
          </checkbox-group>
        </scroll-view>
      </view>
      <view class="no_goods" v-if="goodsList.length == 0">
        <image src="https://yukukeji-oss.oss-cn-beijing.aliyuncs.com/source/XcxShopB1/none_data.png" alt=""
          style="width: 484rpx; height: 484rpx;" mode="aspectFit" />
        <view style="font-size: 26rpx;color: #333333;line-height: 33rpx;margin-bottom: 16rpx;">购物车空空如也</view>
        <view style="font-size: 22rpx;color: #666;line-height: 28rpx;">快去挑选您心仪的商品吧～</view>
      </view>
      <view class="goods_add_box">
        <view class="msgBox" v-if="chajia > 0">
          <text style="font-size: 26rpx;color: #FF1642;">运费</text>
          <text style="font-size: 26rpx;color: #000;margin-right: 8rpx;">凑单</text>
          <text
            style="padding-left: 8rpx;font-weight: 500;font-size: 22rpx;color: #333333;border-left: 1px solid #CCCCCC;">满{{
              selectPrice | parseMoney }}元起送，再买<text style="color:#FF1642;">{{ chajia |
    parseMoney }}</text>元即可配送，快去选购吧！</text>
        </view>
        <view class="goods_add">
          <image src="../../static/shopcar/checked.png" @click="changeAll('2')" v-if="radio == '1'" alt=""
            style="width: 80rpx; height: 80rpx;padding: 15rpx;box-sizing: border-box;" mode="aspectFill" />
          <image src="../../static/shopcar/nochecked.png" @click="changeAll('1')" v-if="radio == '2'" alt=""
            style="width: 80rpx; height: 80rpx;padding: 15rpx;box-sizing: border-box;" mode="aspectFill" />
          <view class="rightBtnBOx" v-if="editStatus === '0'">
            <text style="font-weight: 500;font-size: 28rpx;color: #333333;">合计:</text>
            <PriceFont color="#FF4F30" bigSize="48rpx" smallSize="32rpx" :price="sumPrice" />
            <button class="btn" style="margin-left: 16rpx;padding: 0 24rpx;" @click="onClickButton">去下单({{ count1
            }})</button>
          </view>
          <view class="rightBtnBOx" v-if="editStatus === '1'">
            <!-- <text style="font-weight: 500;font-size: 28rpx;color: #333333;">合计:</text>
            <PriceFont color="#FF4F30" bigSize="48rpx" smallSize="32rpx" :price="sumPrice" /> -->
            <button class="btn" style="margin-left: 16rpx;padding: 0 24rpx;" @click="delGoods">删除({{ count2
            }})</button>
          </view>
        </view>
      </view>
    </view>
    <van-dialog title="删除" :show="showDia" show-cancel-button @confirm="confirmFn" @close="onClose" message="确认移除选中商品吗">
    </van-dialog>
    <van-dialog id="van-dialog" />
  </view>
</template>

<script>
import { getStatus } from '@/utils/auth';
import { DecimalUtils } from "@/utils/math";
import Dialog from 'wxcomponents/vant/dialog/dialog';
import { reqGetCartList, reqAddGoodsToCart, reqDeleteCartGoods, reqGetCartStartPrice } from '@/apis/rexiaogoods'
import app from '@/App.vue'
export default {
  data() {
    return {
      result: [],
      count1: 0,
      count2: 0,
      sumPrice: 0,
      statusBarHeight: app.globalData.statusBarHeight,
      goodsList: [],
      radio: '2',
      // chajia: 0,
      minimum: 0,
      showDia: false,
      selectPrice: 0,
      loading: false,
      Status: '',
      editStatus: '0',
      disabledList: []
    }
  },
  computed: {
    chajia() {
      if (this.selectPrice > this.sumPrice) return DecimalUtils.subtract(this.selectPrice, this.sumPrice)
      else return 0
    }
  },
  onShow() {
    // this.editStatus == '0'
    this.Status = getStatus()
    if (getStatus() == '1') {
      this.reqGetCartList()
      this.reqGetCartStartPrice()
      this.$store.dispatch('user/getCarTotal');
    } else {
      this.goodsList = []
    }
    // this.cancelEditGoods()
    // this.sumFn()
    this.result = this.$store.state.car.activedList
  },
  methods: {
    onClickLeft() {
      uni.navigateBack();
    },
    onChange(e) {
      this.result = e.detail.value
      this.goodsList.map((item, index) => {
        if (this.result.includes(item.id)) {
          item.checked = true
          return {
            ...item,
          }
        } else {
          item.checked = false
          return {
            ...item,
          }
        }
      })
      let stateTrue = 0
      if (this.editStatus == '1') {
        stateTrue = this.goodsList.length
      } else {
        stateTrue = this.goodsList.filter(item => item.state == '0').length
      }
      console.log('eeeeee', this.goodsList);
      // return
      if (this.result.length == stateTrue) {
        this.radio = '1'
      } else {
        this.radio = '2'
      }

      console.log('e.detail.length', this.result.length);
      this.$store.dispatch('car/addActivedList', this.result)
      this.sumFn()
    },
    onClickButton() {
			// let res = await this.$store.dispatch('user/getUserStatus');
			// if(res.code === 200) {
			// 	if(res.data.status == 1){
			// 		uni.utils.toast('请先登录');
			// 		return ;
			// 	}
			// } 
      if (this.result.length === 0) {
        return uni.showToast({ title: '请选择商品', icon: 'none' })
      }
      if (this.chajia > 0) return uni.showToast({ title: '差' + this.chajia + '元起送', icon: 'none' })
      const idStr = this.result.join(',');
      uni.navigateTo({ url: `/packageA/pages/enterOrder/enterOrder?idList=${idStr}` })
      console.log('提交订单');
    },
    async reqGetCartList() {
      this.goodsList = []
      console.log('this.result', this.result);
      const res = await reqGetCartList()
      if (res.code === 200) {
        this.loading = false
        this.disabledList = res.data.filter(item => {
          return item.state == '1'
        })
        let isTrue = 0
        let noTrue = 0
        res.data.forEach(item => {
          if (item.state == '1') {
            if (this.editStatus == '1' && this.result.includes(item.id)) {
              this.goodsList.push({ ...item, checked: true })
            } else {
              if (this.result.includes(item.id)) {
                const index = this.result.findIndex(id => id == item.id)
                if (index != -1) {
                  this.result.splice(index, 1)
                }
              }
              this.goodsList.push({ ...item, checked: false })
            }
          } else {
            if (this.result.includes(item.id)) {
              this.goodsList.push({ ...item, checked: true })
            } else {
              this.goodsList.push({ ...item, checked: false })
            }
          }
        })
        this.$store.dispatch('car/addActivedList', this.result)
        console.log(this.goodsList.length, this.result.length, "@@@@@@@@@@");
        if (this.goodsList.length === 0 || this.result.length == '0') {
          this.editStatus = '0'
          this.radio = '2'
        }
        isTrue = this.goodsList.filter(item => item.state == '0').length
        if (this.editStatus == '0') {
          if (isTrue === this.result.length && this.result.length !== 0) {
            this.radio = '1'
          } else {
            this.radio = '2'
          }
        } else {
          if (this.result.length == this.goodsList.length && this.result.length !== 0) {
            this.radio = '1'
          } else {
            this.radio = '2'
          }
        }
        this.sumFn()
      }
    },
    async onChangecount(e, id, index, ecCommodityId, type) {
      console.log('id', e, id);
      // return
      let c = this.goodsList[index].count
      this.goodsList[index].count = e
      try {
        const res = await reqAddGoodsToCart({
          count: e,
          id: id,
          ecCommodityId: ecCommodityId,
          type: type
        })
        if (res.code === 200) {
          console.log('res', res);
          this.$set(this.goodsList[index], 'count', e)
          this.$store.dispatch('car/addToCar', res.data)
          // console.log('total', this.$store.getters['car/allCount'], this.$store.getters['car/allMoney']);
          this.sumFn()
        }
      } catch (error) {
        this.goodsList[index].count = c
      }
    },
    goToDetail(id, type) {
      console.log('type', type);
      if (type == 1) {
        uni.navigateTo({ url: `/packageA/pages/genericGoodsDetail/genericGoodsDetail?id=${id}` })
      } else {
        uni.navigateTo({ url: `/packageA/pages/goodsDetail/goodsDetail?id=${id}` })
      }
    },
    sumFn() {
      let sum = 0
      let countNum = 0
      this.goodsList.reduce((pre, cur) => {
        if (this.result.includes(cur.id) && cur.state == '0') {
          countNum++
          sum = DecimalUtils.add(sum, DecimalUtils.multiply(cur.count, cur.normsPrice))
        }
        return sum
      }, 0)
      this.$nextTick(() => {
        this.count2 = this.result.length
        this.count1 = countNum
      })
      // if (this.editStatus == '0' && this.count2 !== this.goodsList.length) {
      //   this.radio = '2'
      // }
      console.log('1,2', this.count1, this.count2);
      this.sumPrice = sum
    },
    changeAll(e) {
      this.radio = e
      if (this.radio == '1') {
        this.result = []
        this.goodsList.forEach(item => {
          if (item.state == '0' || this.editStatus == '1') {
            this.result.push(item.id)
            item.checked = true
          }
        })
      } else {
        this.goodsList.forEach(item => item.checked = false)
        this.result = []
      }
      this.$store.dispatch('car/addActivedList', this.result)
      this.count = this.result.length
      this.sumFn()
    },
    // 大型删除按钮删除
    async confirmFn() {
      const res = await reqDeleteCartGoods({ idList: this.result })
      if (res.code === 200) {
        uni.utils.toast('删除成功');
        // if (this.result.length == this.goodsList.length) this.editStatus = '0'
        // console.log('length', this.result.length, this.goodsList.length);
        this.reqGetCartList()
        // this.sumFn()
        this.count = 0
        this.$store.dispatch('car/addToCar', res.data)
        this.$store.dispatch('car/addActivedList', [])
        // 删除成功清空result数组
        this.result = [];
      }
      this.showDia = false
    },
    // 删除图标删除
    delGoodsBtn(id, index) {
      console.log('id', id);
      Dialog.confirm({
        message: '确定删除吗？',
      }).then(async () => {
        const res = await reqDeleteCartGoods({ idList: [id] })
        if (res.code === 200) {
          uni.utils.toast('删除成功');
          let i = this.result.findIndex(item => item == id)
          if (i !== -1) {
            this.result.splice(i, 1)
          }
          // this.sumFn()
          // this.count = this.result.length
          this.$store.dispatch('car/addActivedList', this.result)
          this.$store.dispatch('car/addToCar', res.data)
          this.reqGetCartList()
        }
      }).catch(() => {
        // on cancel
      });
    },
    async delGoods() {
      if (this.result.length == 0) {
        uni.utils.toast('请选择要删除的商品');
        return
      }
      this.showDia = true
    },
    editGoods() {
      this.editStatus = '1'
      // this.$nextTick
      if (this.result.length == this.goodsList.length && this.result.length !== 0) {
        this.radio = '1'
      } else {
        this.radio = '2'
      }
      this.sumFn()
      console.log('编辑', this.result.length, this.goodsList.length, this.radio);
    },
    cancelEditGoods() {
      this.goodsList = this.goodsList.map(item => {
        if (this.result.includes(item.id) && item.state == '1') {
          item.checked = false
          let i = this.result.findIndex(j => j === item.id)
          console.log('需要删除的选中项目', this.result[i]);
          this.result.splice(i, 1)
          return { ...item }
        } else {
          return { ...item }
        }
      })

      this.$store.dispatch('car/addActivedList', this.result)
      const coumI = this.goodsList.filter(item => item.state == '0').length
      if (this.result.length > 0 && this.goodsList.length > 0) {
        if (coumI == this.result.length) {
          this.radio = '1'
        } else {
          this.radio = '2'
        }
      } else {
        this.radio = '2'
      }
      console.log('取消按钮', this.result.length, coumI, this.radio);
      this.editStatus = '0'

    },
    onClose() {
      this.showDia = false
    },
    async reqGetCartStartPrice() {
      const res = await reqGetCartStartPrice()
      if (res.code === 200) {
        console.log('res1111', res);
        this.selectPrice = res.data
      }
    },
    // 左滑删除
    delItemGoods($event, e) {
      const { position, instance } = $event.detail
      Dialog.confirm({
        message: '确定删除吗？',
      }).then(async () => {
        const res = await reqDeleteCartGoods({ idList: [e] })
        if (res.code === 200) {
          uni.utils.toast('删除成功');
          let i = this.result.findIndex(item => item == e)
          if (i !== -1) {
            this.result.splice(i, 1)
          }
          console.log('asdas', this.result, e);
          this.$store.dispatch('car/addActivedList', this.result)
          this.reqGetCartList()
          // this.sumFn()
          // this.count = 0
          this.$store.dispatch('car/addToCar', res.data)
          instance.close();
        }
      }).catch(() => {
        // on cancel
        instance.close();
      });
    },
    refresherrefreshFn() {
      // if (getStatus() == '1') {
      console.log('1111');
      this.loading = true;
      this.reqGetCartList();
      // } else {
      //   this.goodsList = []
      // }
    },

  }
}
</script>
<style>
/* // 复选框形状  */
checkbox .wx-checkbox-input {
  /* // 复选框中对号的位置的更改 */
  margin-right: 8rpx;
  width: 32rpx;
  height: 32rpx;
  border-radius: 50% !important;
  border: 2rpx solid #828181 !important;
}

checkbox .wx-checkbox-input.wx-checkbox-input-checked {
  border: 2rpx solid #FF1642 !important;
  background-color: #FF1642 !important;
  color: #FFFFFF !important;
}

checkbox .wx-checkbox-input.wx-checkbox-input-checked::before {
  color: #FFFFFF !important;
}


/* // 复选框对勾大小、位置 */
radio::before,
checkbox::before {
  /* font-family: "cuIcon"; */
  /* content: "\e645"; */
  position: absolute;
  color: #ffffff !important;
  top: 50%;
  margin-top: -8px;
  margin-left: 7rpx;
  font-size: 24rpx;
  line-height: 32rpx;
  pointer-events: none;
  transform: scale(1, 1);
  transition: all 0.3s ease-in-out 0s;
  z-index: 9;
}

scroll-view ::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
  color: transparent;
}

page {
  background: #f5f5f5;
}
</style>
<style lang="scss" scoped>
view {
  box-sizing: border-box;
}

/deep/ .van-nav-bar {
  background-color: #fff;
}

/deep/ .van-hairline--top-bottom:after {
  border: none !important;
}

/deep/ .van-checkbox__icon {
  font-size: 40rpx !important;
}

.container {
  height: 100%;
  background-color: #F5F5F5;
}

.content {
  // overflow-y: scroll;
  box-sizing: border-box;
  padding: 0 24rpx;
  height: 100vh;
  width: 100%;
  // padding-bottom: 400rpx;
  padding-bottom: 176rpx;

  .goods_list_active {
    padding: 24rpx 24rpx 48rpx 24rpx;
  }

  .goods_list_noactive {
    padding: 24rpx 24rpx 12rpx 24rpx;
  }

  .goods_list {
    background-color: #fff;
    border-radius: 0 0 12rpx 12rpx;
    // padding: 24rpx 24rpx 24rpx 24rpx;
    height: calc(100% - 112rpx);
    // height: 100%;

    // margin-bottom: 176rpx;
    .logo {
      padding-bottom: 24rpx;
      display: flex;
      box-sizing: border-box;
      justify-content: space-between;
      height: 86rpx;

      text {
        height: 100%;
        font-size: 28rpx;
        color: #808080;
        padding: 0 20rpx;
      }
    }

    .goods_item {
      // margin-bottom: 48rpx;
      // padding-bottom: 48rpx;
      display: flex;
      padding: 24rpx 0;
      // justify-content: space-between;
      align-items: center;
      height: 228rpx;
      width: 100%;

      // background-color: palegoldenrod;
      .imgShowBox {
        margin-right: 16rpx;
        position: relative;
        width: 180rpx;
        height: 180rpx;

        .none {
          top: 0;
          left: 0;
          position: absolute;
          width: 180rpx;
          height: 180rpx;
          background: rgba(0, 0, 0, 0.6);
          line-height: 180rpx;
          color: #fff;
          text-align: center;
          font-weight: bold;
          font-size: 28rpx;
        }
      }

      .txtInfo {
        flex: 1;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
        // width: 186rpx;
        height: 100%;
        margin-right: 24rpx;
        // background-color: pink;

        .goods_name {
          font-weight: 600;
          font-size: 28rpx;
          color: #333333;
          line-height: 40rpx;
          width: 326rpx;
          height: 80rpx;
        }

        .goods_deliveryNorms {
          font-weight: 400;
          font-size: 24rpx;
          color: #808080;
          // line-height: 28rpx;
        }

        .goods_price {
          font-family: DINPro, DINPro;
          font-weight: 500;
          font-size: 40rpx;
          color: #FF4F30;
        }

        .countBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
    }

    // .goods_item:nth-last-child(1) {
    //   padding-bottom: 0;
    // }
  }

  // .delBox {
  //   height: 180rpx;
  //   width: 200rpx;
  //   background-color: re;
  // }

  .goods_add_box {

    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #fff;
    margin: 0 auto;

    .msgBox {
      box-sizing: border-box;
      width: 750rpx;
      height: 64rpx;
      line-height: 34rpx;
      background: #FFF0EE;
      padding: 16rpx 24rpx 14rpx;
    }

    .goods_add {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 100rpx;
      padding: 0 24rpx;

      // .imgBox {
      //   width: 100rpx;
      //   height: 100%;
      //   text-align: center;
      //   line-height:100rpx ;
      // }

      .rightBtnBOx {
        font-weight: 700;
        display: flex;
        justify-content: space-between;
        // align-items: end;
        align-items: baseline;

      }

      .btn {
        width: 200rpx;
        height: 76rpx;
        background: #FF1642;
        border-radius: 38rpx 38rpx 38rpx 38rpx;
        line-height: 76rpx;
        font-size: 32rpx;
        color: #FFFFFF;
        letter-spacing: 1px;
      }
    }
  }
}

.delBox {
  height: 228rpx;
  line-height: 228rpx;
  background-color: #ee0a24;
  font-size: 32rpx;
  font-weight: 500;
  color: #fff;
  letter-spacing: 1px;
  width: 65px;
  text-align: center;
}

.no_goods {
  padding-top: 60rpx;
  height: 100%;
  text-align: center;
  background-color: #F5F5F5;
}

/deep/ .van-stepper__input {
  width: 64rpx;
  margin: 0 -2rpx;
  height: 58rpx;
  background: #FFFFFF;
  // border-radius: 4rpx 4rpx 4rpx 4rpx;
  border-top: 2rpx solid #CCCCCC;
  border-bottom: 2rpx solid #CCCCCC;
  line-height: 58rpx;
  ;
  // font-weight: 500;
  font-size: 32rpx;
  color: #333;
  letter-spacing: 1px;
}

/deep/ .van-stepper__minus,
/deep/ .van-stepper__plus {
  width: 60rpx;
  height: 58rpx;
  background: #FFFFFF;
  border: 2rpx solid #CCCCCC;
  border-radius: 6rpx 0 0 6rpx;
  color: #333;
  font-size: 28rpx;
  font-weight: 600;
}

/deep/ .van-stepper__plus {
  border-radius: 0 6rpx 6rpx 0;
}

/deep/ .van-stepper__minus {
  border-radius: 6rpx 0 0 6rpx;
}

/deep/ .van-stepper__minus--disabled {
  background: #FFFFFF !important;
  border: 2rpx solid #CCCCCC;
  color: #b4b4b4;
}
</style>